<template>
  <page-header-wrapper>
    <a-card :bordered="false">
      <!-- 操作 -->
      <div class="table-operations">
        <a-button type="primary" @click="handleExport" v-hasPermi="['angel:subject:export']">
          <a-icon type="download" />导出
        </a-button>
        <!--        <a-button :disabled="!draggable" @click="batchSave">批量保存</a-button>-->
        <a-button @click="addNode">添加</a-button>
        <a-button @click="editNode" type="dashed">修改</a-button>
        <a-button type="danger" @click="oneDelete">选择删除</a-button>
        <a-button type="danger" @click="batchDelete">批量删除</a-button>
        <a-button
          type="dashed"
          shape="circle"
          :loading="loading"
          :style="{float: 'right'}"
          icon="reload"
          @click="getList" />
        <!--        <a-switch :style="{float:'right',marginTop:'8px'}" checked-children="编辑模式" un-checked-children="关闭编辑" @change="switchChange" :checked="draggable"/>-->
      </div>
      <!-- 数据展示 -->
      <a-tree
        showLine
        v-model="checkedKeys"
        checkable=""
        :loading="loading"
        :tree-data="list"
        :default-expanded-keys="expandedKeys"
        :default-selected-keys="selectedKeys"
        :default-checked-keys="checkedKeys"
        :replace-fields="replaceFields"
        @select="onSelect"
        @drop="onDrop"
      >
      </a-tree>
    </a-card>

    <a-drawer
      width="35%"
      title="添加子专业分类"
      placement="right"
      :closable="false"
      :visible="visible"
      @close="closeDrawer"
    >
      <a-form :form="selectNode" layout="vertical" hide-required-mark>
        <a-form-item label="父级名称">
          <a-input placeholder="根" disabled v-model="selectNode.parentName"/>
        </a-form-item>
        <a-form-item label="节点名称">
          <a-input placeholder="" v-model="selectNode.subjectName"/>
        </a-form-item>
        <a-form-item label="节点排序(越大越靠后)">
          <a-input placeholder="" v-model="selectNode.sortNum"/>
        </a-form-item>
        <a-form-item label="节点编号">
          <a-input placeholder="728" v-model="selectNode.subjectNumber"/>
        </a-form-item>
        <div class="bottom-control">
          <a-space>
            <a-button type="primary" @click="submitForm">
              保存
            </a-button>
            <a-button type="dashed" @click="closeDrawer">
              取消
            </a-button>
          </a-space>
        </div>
      </a-form>
    </a-drawer>

    <a-drawer
      width="35%"
      title="修改专业分类"
      placement="right"
      :closable="false"
      :visible="editVisible"
      @close="closeEditDrawer"
    >
      <a-form :form="selectNode" layout="vertical" hide-required-mark>
        <a-form-item label="节点名称">
          <a-input placeholder="请输入要修改的节点名称" v-model="selectNode.subjectName"/>
        </a-form-item>
        <a-form-item label="节点排序(越大越靠后)">
          <a-input placeholder="" v-model="selectNode.sortNum"/>
        </a-form-item>
        <a-form-item label="节点编号">
          <a-input placeholder="728" v-model="selectNode.subjectNumber"/>
        </a-form-item>
        <div class="bottom-control">
          <a-space>
            <a-button type="primary" @click="submitEditForm">
              保存
            </a-button>
            <a-button type="dashed" @click="closeEditDrawer">
              取消
            </a-button>
          </a-space>
        </div>
      </a-form>
    </a-drawer>
  </page-header-wrapper>
</template>

<script>
import { listSubject, delSubject, exportSubject, addSubject, updateSubject, getSubject, delTreeSubject } from '@/api/angel/subject'

export default {
  name: 'Subject',
  data () {
    return {
      list: [],
      draggable: false,
      expandedKeys: [],
      selectedKeys: [],
      checkedKeys: [],
      ids: [],
      loading: false,
      replaceFields: {
        children: 'children',
        title: 'subjectName',
        key: 'id'
      },
      selectNode: {
        id: 0,
        parentName: '',
        subjectName: '',
        subjectNumber: 0,
        parentId: 0,
        sortNum: '1'
      },
      visible: false,
      editVisible: false
    }
  },
  filters: {
  },
  created () {
    this.getList()
  },
  computed: {
  },
  watch: {
  },
  methods: {
    clearDrawer () {
      this.selectNode = {
        id: 0,
        subjectName: '',
        parentId: 0,
        sortNum: 1,
        subjectNumber: 0
      }
    },
    closeEditDrawer () {
      this.editVisible = false
      this.clearDrawer()
    },
    closeDrawer () {
      this.visible = false
      this.clearDrawer()
    },
    /** 查询专业编号列表 */
    getList () {
      this.loading = true
      listSubject().then(response => {
        this.list = response.data
        this.loading = false
      })
    },
    /** 删除按钮操作 */
    handleDelete (row) {
      var that = this
      const ids = row.id || this.ids
      this.$confirm({
        title: '确认删除所选中数据?',
        content: '当前选中编号为' + ids + '的数据',
        onOk () {
          return delSubject(ids)
            .then(() => {
              that.onSelectChange([], [])
              that.getList()
              that.$message.success(
                '删除成功',
                3
              )
          })
        },
        onCancel () {}
      })
    },
    /** 导出按钮操作 */
    handleExport () {
      var that = this
      this.$confirm({
        title: '是否确认导出?',
        content: '此操作将导出当前条件下所有数据而非选中数据',
        onOk () {
          return exportSubject(that.queryParam)
            .then(response => {
              that.download(response.msg)
              that.$message.success(
                '导出成功',
                3
              )
          })
        },
        onCancel () {}
      })
    },
    /** select 属性函数 */
    onSelect (selectedKeys, { node }) {
      this.selectNode.parentId = selectedKeys[0]
      this.selectNode.parentName = node.title
    },
    addNode () {
      this.visible = true
    },
    async editNode () {
      const res = await getSubject(this.selectNode.parentId)
      if (res.code !== 200) {
        this.$message.success(
          '加载数据失败',
          3
        )
        this.closeEditDrawer()
        return false
      }
      this.selectNode.subjectName = res.data.subjectName
      this.selectNode.subjectNumber = res.data.subjectNumber
      this.selectNode.sortNum = res.data.sortNum
      this.selectNode.id = res.data.id
      this.selectNode.parentId = res.data.parentId
      this.editVisible = true
    },
    // 提交添加
    /** 提交按钮 */
    submitForm () {
      addSubject(this.selectNode).then(response => {
        this.$message.success(
          '新增成功',
          3
        )
        this.visible = false
        this.clearDrawer()
        this.getList()
      })
    },
    submitEditForm () {
      updateSubject(this.selectNode).then(response => {
        this.$message.success(
          '修改成功',
          3
        )
        this.editVisible = false
        this.clearDrawer()
        this.getList()
      })
    },
    batchDelete () {
      const chks = this.checkedKeys
      const that = this
      this.$confirm({
        title: '确认删除所选中数据?',
        content: '当前选中id为' + chks + '的数据',
        onOk () {
          return delSubject(chks)
            .then(() => {
              that.getList()
              that.$message.success(
                '删除成功',
                3
              )
            })
        },
        onCancel () {}
      })
    },
    oneDelete () {
      const id = this.selectNode.parentId
      if (id === undefined || id === 0) {
        this.$message.info(
          '未选择任何节点',
          3
        )
        return false
      }
      const that = this
      this.$confirm({
        title: '确认删除所选中数据?',
        content: '当前选中为' + this.selectNode.parentName + '的数据,注意此节点和其子节点都会被删除',
        onOk () {
          return delTreeSubject(id)
            .then(() => {
              that.getList()
              that.$message.success(
                '删除成功',
                3
              )
            })
        },
        onCancel () {}
      })
    },
    switchChange (draggable) {
      this.draggable = draggable
    },
    onDrop (info) {
      const dropKey = info.node.eventKey
      const dragKey = info.dragNode.eventKey
      const dropPos = info.node.pos.split('-')
      const dropPosition = info.dropPosition - Number(dropPos[dropPos.length - 1])
      const loop = (data, key, callback) => {
        data.forEach((item, index, arr) => {
          if (item.id === key) {
            return callback(item, index, arr)
          }
          if (item.children) {
            return loop(item.children, key, callback)
          }
        })
      }
      const data = [...this.list]

      // Find dragObject
      let dragObj
      loop(data, dragKey, (item, index, arr) => {
        arr.splice(index, 1)
        dragObj = item
      })
      if (!info.dropToGap) {
        // Drop on the content
        loop(data, dropKey, item => {
          item.children = item.children || []
          // where to insert 示例添加到尾部，可以是随意位置
          item.children.push(dragObj)
        })
      } else if (
        (info.node.children || []).length > 0 && // Has children
        info.node.expanded && // Is expanded
        dropPosition === 1 // On the bottom gap
      ) {
        loop(data, dropKey, item => {
          item.children = item.children || []
          // where to insert 示例添加到尾部，可以是随意位置
          item.children.unshift(dragObj)
        })
      } else {
        let ar
        let i
        loop(data, dropKey, (item, index, arr) => {
          ar = arr
          i = index
        })
        if (dropPosition === -1) {
          ar.splice(i, 0, dragObj)
        } else {
          ar.splice(i + 1, 0, dragObj)
        }
      }
      this.list = data
    }
  }
}
</script>
